import 'dart:async';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:card_swiper/card_swiper.dart';
import 'package:path_provider/path_provider.dart';
import 'package:process_run/cmd_run.dart';
import 'package:self32/http/api.dart';
import 'package:self32/page/borrow_page.dart';
import 'package:self32/page/mine_page.dart';
import 'package:self32/page/return_page.dart';
import 'package:self32/util/toast_util.dart';

import '../main.dart';
import '../util/analysis_book_rule.dart';
import '../widget/app_bar.dart';
import 'borrow_again_page.dart';
import 'query_page.dart';



class Index extends StatefulWidget {
  const Index({Key? key}) : super(key: key);

  @override
  State<Index> createState() => _IndexState();
}

class _IndexState extends State<Index> {

  final RxList<String> recommendList = RxList();

  final RxList<String> bannerList = RxList();


  @override
  initState() {
    super.initState();

    // socketHelper.add(checkReader());
    print('version = $version');

    _getVersion();

    _loadRecommend();
    _loadBanner();
  }

  _getVersion() async {
    getVersion().then((value) async {
      if(value != null){
        int code = value.verCode??0;
        if(code > versionCode){
          _update();
        }
      }
    });
  }


  _update() async {
    // 替换以下路径为你的exe文件路径
    var executable = '${settingEntity.executable}\\Updater.exe';
    var arguments = <String>['-app:self32', '-host:${settingEntity.sip2ApiAddr}', '-device_id:${settingEntity.deviceNo?.replaceAll('device_id=', '')}', '-kind:library']; // 如果需要传递参数，则添加到这个列表中

    // 启动外部exe文件
    var result = await runExecutableArguments(executable, arguments);

    // 打印输出
    print('Exit code: ${result.exitCode}');
    print('Stdout: ${result.stdout}');
    print('Stderr: ${result.stderr}');
  }

  Future _loadBanner() async {
    final directory = await getApplicationDocumentsDirectory();
    final directoryPath = '${directory.path}/banner';

    final directoryList = Directory(directoryPath);
    final fileList = directoryList.list();

    await for (final fileEntity in fileList) {
      final fileName = fileEntity.uri.toString().split('/').last;
      bannerList.add('$directoryPath/$fileName');
    }
  }

  Future _loadRecommend() async {

    final directory = await getApplicationDocumentsDirectory();
    final directoryPath = '${directory.path}/recommend';

    final directoryList = Directory(directoryPath);
    final fileList = directoryList.list();

    await for (final fileEntity in fileList) {
      final fileName = fileEntity.uri.toString().split('/').last;
      recommendList.add('$directoryPath/$fileName');
    }
  }


  @override
  void dispose() {
    clock.cancel();
    super.dispose();
  }

  _swiper(){
    return Container(
      height: 115.h,
      margin: EdgeInsets.only(top: 8.r,left: 8.r,right: 8.r),
      child: Obx(() => Swiper(
        itemBuilder: (BuildContext context,int index){
          return Container(
            clipBehavior: Clip.hardEdge,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(8),
            ),
            // child: Image.network("$apiUrl/${bannerList[index]}", fit: BoxFit.cover,),
            child: Image.file(File(bannerList[index]), fit: BoxFit.cover,),
          );
        },
        itemCount: bannerList.length,
        itemWidth: 360.w,
        itemHeight: 115.h,
        autoplay: true,
        autoplayDelay: 5000,
        // layout: SwiperLayout.STACK,
        pagination: const SwiperPagination(),
        // control: SwiperControl(),
      )),
    );
  }

  _action(){
    return Padding(padding: EdgeInsets.only(left: 8.r,right: 8.r,top: 8.r),
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              InkWell(
                onTap: (){
                  Get.to(()=> const Borrow());

                },
                child: Image.asset("assets/images/borrow_bg.png",width:192.w,fit: BoxFit.fitWidth,),
              ),
              Column(
                children: [
                  InkWell(
                    onTap: (){
                      Get.to(()=> const Return());
                    },
                    child: Image.asset("assets/images/return_bg.png",width:192.w,fit: BoxFit.fitWidth,),
                  ),
                  SizedBox(height: 8.r,),
                  Row(
                    children: [
                      InkWell(
                        onTap: (){
                          Get.to(()=> const BorrowAgain());
                        },
                        child: Image.asset("assets/images/borrow_again_bg.png",width:91.w,fit: BoxFit.fitWidth,),
                      ),
                      SizedBox(width: 8.r,),
                      InkWell(
                        onTap: (){
                          toastWarn('功能暂不开放');
                          // Get.to(()=> const RegisterSelect());
                        },
                        child: Image.asset("assets/images/auth_bg.png",width:91.w,fit: BoxFit.fitWidth,),
                      ),
                    ],
                  )
                ],
              )
            ],
          ),
          SizedBox(height: 8.r,),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              InkWell(
                onTap: (){
                  Get.to(()=> const Query());
                },
                child: Image.asset("assets/images/query_bg.png",width:192.w,fit: BoxFit.fitWidth,),
              ),

              InkWell(
                onTap: (){
                  Get.to(()=> const Mine());
                },
                child: Image.asset("assets/images/mine_bg.png",width:192.w,fit: BoxFit.fitWidth,),
              ),
            ],
          )
        ],
      ));
  }


  _rank(){
    return Container(
      width: double.infinity,
      height: 152.h,
      margin: EdgeInsets.only(left:8.r,right: 8.r,top: 8.r),
      decoration:  BoxDecoration(
        color: const Color.fromRGBO(255, 255, 255, 0.4),
        borderRadius: BorderRadius.all(Radius.circular(4.r)),
      ),
      padding: EdgeInsets.only(left:8.r,right: 8.r,top: 8.r),
      child: Column(
        // crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(
            width: 386.w,
            height: 20.h,
            child: Stack(
              alignment: AlignmentDirectional.center,
              children: [
                Positioned(left:0,child: Text('图书推荐',style: TextStyle(fontSize: 13.sp,color: Colors.white),))
              ],
            ),
          ),
          SizedBox(
              height: 116.h,
              child: Obx(() => ListView.separated(
                itemBuilder: (context, index) {
                  return _listItem(index);
                },
                scrollDirection: Axis.horizontal,
                itemCount: recommendList.length,
                separatorBuilder: (BuildContext context, int index) {
                  return VerticalDivider(
                      width: 8.w,
                      color: Colors.transparent);
                },
              ))
          )
        ],
      ),
    );
  }

  _listItem(index){
    return Container(
        margin: EdgeInsets.only(top: 8.r),
        child:  Image.file(File(recommendList[index]),height:90.h,fit: BoxFit.fitHeight,),
    );
  }

  _version(){
    return Container(
        margin: EdgeInsets.only(top: 6.r,left: 8.r,right: 8.r),
        child: Align(child: Text('版本号$version',style: TextStyle(color: Colors.white,fontSize: 8.sp)),)
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: [
          Container(
              width: double.infinity,
              height: double.infinity,
              decoration: const BoxDecoration(
                image: DecorationImage(
                  fit: BoxFit.fill,
                  image: AssetImage(
                    "assets/images/bg.png",
                  ),
                ),
              ),
              child: Column(
                children: [
                  appBar(isIndex: true),
                  _swiper(),
                  _action(),
                  _rank(),
                  _version()
                  // _version(),
                ],
              )
          ),

        ]
      )
    );
  }
}